import json
import urllib.error
import urllib.request


class ScoreboardClient:
    def __init__(self, api_key, collection, base_url=None, logger=None):
        self.api_key = api_key
        self.collection = collection
        self.base_url = base_url or "https://sagegames-0c86.restdb.io/rest"
        self.logger = logger

    def post_score(self, payload):
        request = urllib.request.Request(
            f"{self.base_url.rstrip('/')}/{self.collection}",
            data=json.dumps(payload).encode("utf-8"),
            headers={
                "content-type": "application/json",
                "x-apikey": self.api_key,
                "cache-control": "no-cache",
            },
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=10) as response:
                status_code = getattr(response, "status", 200)
                return 200 <= status_code < 300
        except urllib.error.URLError as exc:
            if self.logger:
                self.logger.error(f"Failed to post Hand Flop score: {exc}")
            return False
